package com.zjw.zy.base;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.zjw.zy.utils.PathUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/10/10 9:04
 */
public class ImageEditText extends androidx.appcompat.widget.AppCompatEditText {


    private static final String TAG = "ImageEditText";
    public final static String IMAGE_PRE = "$image{";
    public final static String IMAGE_SUFFIX = "}$";

    private int imageWidth = 500;
    private int imagePaddingStart = 0;

    private final List<Bitmap> bitmapList = new ArrayList<>();


    public ImageEditText(Context context) {
        super(context);
    }

    public ImageEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        processImageClick(event);
        return super.onTouchEvent(event);
    }

    private void processImageClick(MotionEvent event) {

    }

    /**
     * 文本格式~
     * <p>
     * 秋天的第一场雪 $image{path} 原来如此
     */
    public void setTextWithImage(@Nullable CharSequence text) {
        String src = text == null ? "" : text.toString();

        //解析出image
        List<String> srcs = parseToImageUrls(src);

        //移除bitmap
        recycleBitmap();

        this.setText("");

        for (String item : srcs) {
            if (item.startsWith(IMAGE_PRE)) {
                //图片
                appendImage(parseImageUrl(item));
            } else {
                //普通文字
                append(item);
            }
        }
    }

    private void recycleBitmap() {
        for (Bitmap bitmap : bitmapList) {
            bitmap.recycle();
        }
        bitmapList.clear();
    }

    /**
     * 分离出imageUrl
     */
    private List<String> parseToImageUrls(String src) {
        if (src == null || src.isEmpty()) {
            return Collections.emptyList();
        }

        int startIndex = 0;

        List<String> result = new ArrayList<>();

        while (startIndex >= 0) {
            int index = src.indexOf(IMAGE_PRE, startIndex);
            int end = -1;
            if (index >= 0) {
                end = src.indexOf(IMAGE_SUFFIX, index);
            }

            if (end >= 0) {
                //find one
                if (index > startIndex) {
                    //存入非image文本
                    result.add(src.substring(startIndex, index));
                }
                result.add(src.substring(index, end + IMAGE_SUFFIX.length()));
                startIndex = end + IMAGE_SUFFIX.length();
            } else {
                //存入非image文本
                result.add(src.substring(startIndex));
                startIndex = -1;
            }
        }

        return result;
    }

    public void appendImage(@NonNull Uri image) {
        String path = PathUtils.getImageRealPathFromURI(image);
        appendImage(path);
    }

    public void appendImage(@NonNull String path) {
        String imageUrl = IMAGE_PRE + path + IMAGE_SUFFIX;
        SpannableStringBuilder ss = new SpannableStringBuilder(imageUrl);

        Bitmap bitmap = PathUtils.getBitmapFromPath(path);
        //保存一份，需要回收
        if (bitmap == null) {
            Log.e(TAG, "appendImage: bitmap == null");
            return;
        }
        bitmapList.add(bitmap);
        ImageSpan span = new ImageSpan(getContext(), bitmap, ImageSpan.ALIGN_BASELINE);
        Drawable drawable = span.getDrawable();
        //修正图片显示大小
        int intrinsicWidth = drawable.getIntrinsicWidth();
        int intrinsicHeight = drawable.getIntrinsicHeight();
        double alpha = imageWidth * 1.0 / intrinsicWidth;
        drawable.setBounds(imagePaddingStart, 0, imageWidth + imagePaddingStart,
                (int) (intrinsicHeight * alpha));

        ss.setSpan(span, 0, imageUrl.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        this.append(ss);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        recycleBitmap();
    }

    /**
     * 设置图片存放宽度
     */
    public void setImageWidth(int contentWidth) {
        this.imageWidth = contentWidth;
    }

    /**
     * 设置图片左边距
     */
    public void setImagePaddingStart(int paddingStart) {
        this.imagePaddingStart = paddingStart;
    }

    /**
     * 返回$image{path}$中path
     */
    private String parseImageUrl(@NonNull String imageUrl) {
        return imageUrl.substring(IMAGE_PRE.length(), imageUrl.length() - IMAGE_SUFFIX.length());
    }

}
